<template>
  <!-- ============================================用户管理====================================== -->
  <el-container>
    <el-header style="height: 40px;padding-right: 10px;">
      <div style="display: flex;align-items: center;height: 40px;">
        <div style="flex-grow:1;font-size: 16px;font-weight: bold;">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item v-for="(item, index) in breadcrumb" :key="index">{{ item }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div style="display:flex;align-items: center;">
          <div style="margin-right:15px;">
            <el-input @input="keyWordSerach()" v-model="searchData.keyWord" size="small" placeholder="关键字搜索" />
          </div>
          <!-- <el-input @input="keyWordSerach()" v-model="searchData.keyWord" size="small" placeholder="关键字搜索" /> -->
          <el-button-group style="margin-right:15px;">
            <el-button size="small" type="primary" icon="Search" @click="btnSearch()">查询</el-button>
            <el-button size="small" type="primary" icon="ArrowDownBold" @click="isshowdrawer = true"></el-button>
          </el-button-group>
          <el-button size="small" type="info" icon="Refresh" plain @click="reset()">重置</el-button>
          <el-button size="small" type="success" icon="CirclePlus" @click="addData()">新建</el-button>
        </div>
      </div>
    </el-header>
    <el-main>
      <el-table ref="tableRef" 
      height="100%"
      :data="tableData"
      :row-style="(e) => $store.state.tableRowStyle(e, rowStyle)"
      :header-cell-style="$store.state.outheaderstyle"
      @row-click="rowClick"
      @filter-change="filterChange" 
      @selection-change="handleSelectionChange" 
      @cell-dblclick="cellDBClick"
      @sort-change="sortChange"
      @row-contextmenu="rowContextMenu"
      row-key="id"
      size="small">
        <el-table-column type="selection"></el-table-column>
        <el-table-column :filters="filterData.enterpriseState" 
          prop="enterpriseState" label="企业状态" width="100" 
          column-key="enterpriseState"
          show-overflow-tooltip>
          <template #default="scope">
            <el-tag size="small" v-show="scope.row.enterpriseState == '1'" type="primary" effect="dark">正式企业</el-tag>
            <el-tag size="small" v-show="scope.row.enterpriseState == '2'" type="warning" effect="dark">试用企业</el-tag>
            <el-tag size="small" v-show="scope.row.enterpriseState == '3'" type="danger" effect="dark">过期企业</el-tag>
            <el-tag size="small" v-show="scope.row.enterpriseState == '4'" type="success" effect="dark">活跃企业</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enterpriseName" label="企业名称" 
          column-key="enterpriseName" width="150"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="enterpriseFullName" label="企业全名" 
          column-key="enterpriseFullName" width="200"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="enterpriseCode" label="企业代码" 
          column-key="enterpriseCode" width="150"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="enterpriseMobile" label="企业注册手机号" 
          column-key="enterpriseMobile" width="150"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="maxNum" label="最大账户数量" 
          column-key="maxNum" width="150"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="createTime" label="企业注册日期" 
          column-key="createTime" width="150"
          show-overflow-tooltip>
          <template #default="scope">
            {{ $filters.DateFilter(scope.row.createTime, 'yyyy-MM-dd') }}
          </template>
        </el-table-column>
        <el-table-column prop="lastTime" label="企业最后使用日期" 
          column-key="lastTime" width="200"
          show-overflow-tooltip>
          <template #default="scope">
            {{ $filters.DateFilter(scope.row.lastTime, 'yyyy-MM-dd') }}
          </template>
        </el-table-column>
        <el-table-column prop="remainDays" label="企业剩余天数" 
          column-key="remainDays" width="150"
          show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.remainDays }}天
            <!-- {{ $filters.DateFilter(scope.row.expireTime, 'yyyy-MM-dd') }} -->
          </template>
        </el-table-column>

        <el-table-column align="center" width="480px" fixed="right" label="操作">
          <!-- <template #header>
            <el-input @input="keyWordSerach()" v-model="searchData.keyWord" size="small" placeholder="关键字搜索" />
          </template> -->
          <template #default="scope">

            <div style="display: flex;align-items: center;justify-content: flex-end;">

              <!-- <el-button size="small" @click="giveKeyFn(scope.$index, scope.row)">分发密钥</el-button> -->

              <el-dropdown split-button size="small" type="primary" @click="giveKeyFn(scope.$index, scope.row)" style="margin-right: 12px;">
                分发密钥
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item><span @click="showKeyList(scope.$index, scope.row)">密钥列表</span></el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <el-dropdown split-button size="small" type="primary" @click="showDetail(scope.$index, scope.row)" style="margin-right: 12px;">
                展示企业名片
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item><span @click="gotoUser(scope.$index, scope.row)">企业成员</span></el-dropdown-item>
                    <el-dropdown-item><span @click="gotoRole(scope.$index, scope.row)">企业角色</span></el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              
              <!-- <el-button size="small" @click="showDetail(scope.$index, scope.row)">展示企业名片</el-button>
              <el-button size="small" @click="gotoUser(scope.$index, scope.row)">企业成员</el-button>
              <el-button size="small" @click="gotoRole(scope.$index, scope.row)">企业角色</el-button> -->
              <el-button size="small" v-if="scope.row.enterpriseState == '2'" type="success" @click="checkCompany(scope.$index, scope.row)">正式签约</el-button>
              <el-button size="small" v-if="scope.row.enterpriseState == '1'" type="warning" @click="moreDate(scope.$index, scope.row)">企业续费</el-button>
              <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row, 1)">删除</el-button>
            </div>
            
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer>
      <div style="display: flex;align-items: center;height: 45px;">
        <div style="flex-grow: 1">
          <el-button size="small" style="" type="danger" icon="Delete" @click.stop="deletechoose">批量删除</el-button>
        </div>
        <el-pagination
          size="small"
          v-model:currentPage="searchData.page"
          v-model:page-size="searchData.limit"
          :page-sizes="searchData.pageSizes"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="searchData.totalItemCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-footer>
    <!-- =================================== 弹出层 ================================ -->
    <el-dialog custom-class="diyDialog" class="diyDialog" 
    v-model="openDialog" :before-close="(done) => beforeClose(done)" 
    destroy-on-close
    title="列表详情" width="1050px">
    
      <div class="contentbox_border border" :style="'max-height: ' + ($store.state.dialog_body_height) + 'px;overflow-y: auto;'">

        <key-list v-if="dialogSwitch == 'key_list'" ref="key_list" @close-dialog="closeDialog"></key-list>
        <give-key v-if="dialogSwitch == 'give_key'" ref="give_key" @close-dialog="closeDialog"></give-key>
        <data-detail v-if="dialogSwitch == 'data_detail'" ref="data_detail" @close-dialog="closeDialog" @refreshData="getData()"></data-detail>
        <show-enterprise-info v-if="dialogSwitch == 'show_enterprise_info'" ref="show_enterprise_info" @close-dialog="clickClose"></show-enterprise-info>
        <!-- <user-info v-if="dialogSwitch == 'user_info'" ref="user_info" @close-dialog="clickClose"></user-info> -->

      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button v-if="dialogSwitch == 'give_key'" type="primary" @click="saveData_1()">保存</el-button> -->
          <el-button v-if="dialogSwitch == 'data_detail' || dialogSwitch == 'give_key'" type="primary" @click="saveData()">保存</el-button>
          <el-button @click="clickClose()">关闭</el-button>
        </div>
      </template>

    </el-dialog>
    <el-dialog
      v-model="dialogVisible"
      title="设置日期"
      width="350"
    >
      <el-input
        @wheel="(evt) => $utils.disableWheel(evt)" 
        type="number"
        v-model="setdate.expireTime"
        style="max-width: 600px"
        placeholder="请输入天数"
        class="diyinput"
      >
        <template #append>
          <el-select v-model="setdate.expireTimeUnit" placeholder="请选择单位" style="width: 115px">
            <el-option label="年" value="year" />
            <el-option label="月" value="month" />
          </el-select>
        </template>
      </el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="setDateUnit()">
            确定{{ dateBtnText }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- =========================================================================== -->

    <el-drawer
      v-model="isshowdrawer"
      title="高级筛选"
      direction="rtl"
      :before-close="drawerHandleClose"
    >
      <div class="flexbox" style="margin-bottom:10px;">
        <div class="searchContent">企业名称：</div>
        <div class="searchBox" style="width:100%;">
          <el-input placeholder="请输入企业名称" v-model="searchData.enterpriseName"></el-input>
        </div>
      </div>
      <div class="flexbox" style="margin-bottom:10px;">
        <div class="searchContent">企业代码：</div>
        <div class="searchBox" style="width:100%;">
          <el-input placeholder="请输入企业代码" v-model="searchData.enterpriseCode"></el-input>
        </div>
      </div>
      <div class="flexbox" style="margin-bottom:10px;">
        <div class="searchContent">手机号码：</div>
        <div class="searchBox" style="width:100%;">
          <el-input placeholder="请输入手机号码" v-model="searchData.enterpriseMobile"></el-input>
        </div>
      </div>

      <div class="flexbox" style="margin-bottom:10px;">
        <div class="searchContent">注册日期：</div>
        <div class="searchBox" style="width:100%;">
          <el-date-picker
            v-model="searchData.createTime"
            type="daterange"
            start-placeholder="起始日期"
            end-placeholder="结束日期"
          />
        </div>
      </div>

      <div class="flexbox" style="margin-bottom:10px;">
        <div class="searchContent">过期日期：</div>
        <div class="searchBox" style="width:100%;">
          <el-date-picker
            v-model="searchData.expireTime"
            type="daterange"
            start-placeholder="起始日期"
            end-placeholder="结束日期"
          />
        </div>
      </div>

      <div class="flexbox" style="margin-bottom:10px;">
        <div class="searchContent">最后使用日期：</div>
        <div class="searchBox" style="width:100%;">
          <el-date-picker
            v-model="searchData.lastTime"
            type="daterange"
            start-placeholder="起始日期"
            end-placeholder="结束日期"
          />
        </div>
      </div>

      <template #footer>
        <div style="flex: auto">
          <el-button size="small" @click="isshowdrawer=false">关闭</el-button>
          <el-button size="small" type="info" icon="Refresh" @click="reset()">重置</el-button>
          <el-button size="small" type="primary" @click="btnSearch()">查询</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- ====================================右键菜单================================== -->
    <context-menu-pop>
      <template #pop_body>
        <div style="cursor: pointer;padding:3px 0;font-size: 14px;">
          <div class="clickitem">
            <div class="itemleft">功能1</div>
            <div class="itemright"></div>
          </div>
          <div class="clickitem">
            <div class="itemleft">功能2</div>
            <div class="itemright"></div>
          </div>
          <div class="clickitem">
            <div class="itemleft">功能3</div>
            <div class="itemright"></div>
          </div>
          <div class="clickitem">
            <div class="itemleft">功能4</div>
            <div class="itemright"></div>
          </div>
        </div>
        
      </template>
    </context-menu-pop>


  </el-container>
</template>

<script setup>
  import DataDetail from './detail.vue'
  import GiveKey from './giveKeys.vue'
  import KeyList from './keyList.vue'
  import ShowEnterpriseInfo from './showEnterpriseInfo.vue'
  import ContextMenuPop from '@/components/Jm_ContextMenu/jm_popMenu.vue'
  import { reactive, ref, onMounted, inject, nextTick } from 'vue'
  import { useStore } from 'vuex'
  import { useRouter } from 'vue-router'
  const router = useRouter()
  // 注入全局utils工具js
  const $utils = inject('$utils')
  // 注入全局filters工具js
  const $filters = inject('$filters')
  // 定义store
  const store = useStore()
  // 设置行的颜色，空值为默认值
  const rowStyle = reactive({ id: '', color: '' })
  // 
  const dialogSwitch = ref('')

  // 定义子组件的ref
  const data_detail = ref()
  const show_enterprise_info = ref()
  const give_key = ref()
  const key_list = ref()
  // const user_info = ref()
  
  // 定义定时器
  const timmer = ref(null)

  // *********************************定义变量**********************************
  // 页眉
  const breadcrumb = ref(['企业管理'])
  // 是否开启详细查询
  const isshowdrawer = ref(false)
  // 筛选条件分布
  const filterData = ref({
    enterpriseState: [
      { text: '正式企业', value: '1' },
      { text: '试用企业', value: '2' },
      { text: '过期企业', value: '3' },
      { text: '活跃企业', value: '4' }
    ]
  })
  // 定义table的ref绑定
  const tableRef = ref()
  // 筛选条件
  const searchData = ref({
    page: 1,
    pageSizes: [30, 100, 200, 300, 400],
    limit: 30,
    totalItemCount: 100,
    keyWord: ''
  })
  // 批量选择的数据
  const chooseTableData = ref()
  // 初始化表格数据
  const tableData = ref([])
  // 是否开启弹窗
  const openDialog = ref(false)

  // 确定签约
  const dateBtnText = ref('签约')
  const dialogVisible = ref(false)
  const setdate = ref({
    expireTime: '1',
    expireTimeUnit: 'year',
    enterpriseId: '',
    url: '',
    dateIndex: ''
  })
  // ***************************************************************************

  // 进入该模块执行的方法
  const onMountedHook = function () {
    if (store.state.isOldRouter || store.state.routerMode_refrash) {
      getData()
    }
  }

  // ****************************************************************************
  // ------------------ 右键菜单事件 ---------------------------
  function rowContextMenu(row, column, event) {
    // event.preventDefault()
    // rowStyle.id = row.id
    // store.commit('set_pop_attr', {
    //   pop_show: true, 
    //   get_event: event 
    // })
  }
  // ****************************************************************************************************************************
  function showKeyList (index, item) {
    // openDialog.value = true
    showView('key_list')
    // 等待组件渲染完成
    nextTick(() => {
      key_list.value.initData(item.id)
    })
  }

  function giveKeyFn (index, item) {
    // openDialog.value = true
    showView('give_key')
    // 等待组件渲染完成
    nextTick(() => {
      give_key.value.initData({
        type: 'edit',
        data: item
      })
    })
  }
  // 展示企业名片
  async function showDetail(index, item) {
    const res = await getEntInfo(item)
    if (res.data.code == 0) {
      showView('show_enterprise_info')
      // 等待组件渲染完成
      await nextTick()
      show_enterprise_info.value.initData({
        data: res.data.data
      })
    }
    console.log(res)
  }
  function getEntInfo(item) {
    return $utils.post({
      url: '/Api/Enterprise/GetEntInfo',
      params: {
        id: item.id
      },
      noasync: true,
      showLoading: true
    })
  }
  // 展示企业成员
  function gotoUser(index, item) {
    router.push({
      name: 'user',
      state: {
        companyId: item.id,
        companyName: item.enterpriseFullName
      }
    })
  }

  // 展示企业角色
  function gotoRole(index, item) {
    router.push({
      name: 'role',
      state: {
        companyId: item.id,
        companyName: item.enterpriseFullName
      }
    })
  }

  // 正式签约
  function checkCompany(index, item) {
    dateBtnText.value = '签约'
    dialogVisible.value = true
    setdate.value.enterpriseId = item.id
    setdate.value.url = '/Api/Enterprise/Sign'
    setdate.value.dateIndex = index
  }

  // 企业续费
  function moreDate(index, item) {
    dateBtnText.value = '续费'
    dialogVisible.value = true
    setdate.value.enterpriseId = item.id
    setdate.value.url = '/Api/Enterprise/Pay'
    setdate.value.dateIndex = index
  }

  function setDateUnit () {
    $utils.post({
      url: setdate.value.url,
      showLoading: true,
      confirm: true,
      confirmText: `是否确定${dateBtnText.value}？`,
      params: setdate.value,
      ok: function (res) {
        dialogVisible.value = false
        getData()
      }
    })
  }
  

  // *****************************************************************************************************************

  // 保存数据提交方法
  function saveData() {
    eval(`${dialogSwitch.value}.value.submitData()`)
  }
  // 输入关键字查询
  function keyWordSerach() {
    if (timmer.value) {
      clearTimeout(timmer.value)
    }
    timmer.value = setTimeout(() => {
      btnSearch()
    }, 300)
  }
  // 查询第一页数据方法
  function btnSearch() {
    searchData.value.page = 1
    getData()
  }
  // 获取数据方法
  function getData() {
    tableData.value = []
    $utils.post({
      url: '/Api/Enterprise/GetPageList',
      // isGet: true,
      params: searchData.value,
      ok: function (res) {
        tableData.value = res.data
        searchData.value.totalItemCount = res.count
      }
    })
  }
  // 新建列表方法
  async function addData() {
    // openDialog.value = true
    showView('data_detail')
    await nextTick()
    data_detail.value.initData({
      type: 'add'
    })
  }
  // 编辑数据方法
  async function handleEdit(index, item) {
    // 查询详情数据
    const res = await getPageData(item)
    if (res.data.code == 0) {
      // openDialog.value = true
      showView('data_detail')
      // 等待组件渲染完成
      await nextTick()
      data_detail.value.initData({
        data: res.data.data.model,
        type: 'edit'
      })
    }
  }
  // 删除数据方法
  function handleDelete(item, flag) {
    // 删除方法相应的字段
    const del_Id = 'id'
    const ids = []
    if (flag == 0) {
      item.forEach(item => {
        ids.push(item[del_Id])
      })
    } else {
      ids.push(item[del_Id])
    }
    $utils.post({
      url: '/Api/Enterprise/DoBatchDelete',
      params: { id: ids },
      confirm: true,
      showLoading: true,
      ok: function (res) {
        getData()
      }
    })
  }
  // 批量删除数据方法
  function deletechoose() {
    if (chooseTableData.value.length == 0) {
      $utils.message({
        showClose: true,
        center: true,
        message: '请选择操作数据',
        type: 'warning'
      })
    } else {
      handleDelete(chooseTableData.value, 0)
    }
  }
  function getPageData(item) {
    return $utils.post({
      url: '/Api/Enterprise/GetEdit',
      params: {
        id: item.id
      },
      showLoading: true,
      noasync: true
    })
  }
  // ====================== 关闭弹窗事件 ===========================
  // 筛选展示的弹窗组件
  function showView(type) {
    openDialog.value = true
    dialogSwitch.value = type
  }
  function beforeClose(done, flag) {
    if (flag || store.state.close_showtip) {
      $utils.showCloseTip(function () {
        done()
        getData()
      })
    } else {
      done()
      getData()
    }
  }
  function closeDialog(flag) {
    openDialog.value = flag
    getData()
  }
  function clickClose() {
    openDialog.value = false
  }
  // *******************************修改分页*******************************
  // 改变每页条数方法
  function handleSizeChange(val) {
    searchData.value.limit = val
    getData()
  }
  // 改变页数方法
  function handleCurrentChange(val) {
    searchData.value.page = val
    getData()
  }
  // **************************************************************

  // *******************************Table操作*******************************
  // 多选数据
  function handleSelectionChange(val) {
    chooseTableData.value = val
  }
  // 行单击事件
  function rowClick(row, column, e) {
    rowStyle.id = row.id
  }
  // 标题头筛选
  function filterChange(filters) {
    const key = Object.keys(filters)[0]
    searchData.value[key] = filters[key]
    getData()
  }
  // 行双击事件
  function cellDBClick(row, column, cell, event) {
    handleEdit(1, row)
  }
  // 排序筛选
  function sortChange(obj) {
    if (!obj.prop) {
      searchData.value.orderBy = ''
    } else {
      searchData.value.orderBy = obj.prop + ' ' + obj.order
    }
    getData()
  }
  // 重置查询条件方法
  function reset() {
    tableRef.value.clearFilter()
    searchData.value = $utils.resetForm(searchData.value)
  }
  // **************************************************************

  onMounted(() => {
    onMountedHook()
  })

</script>

<style scoped>
.el-container {
  height: 100%;
}
.el-header {
  background-color:#fff;
  border:1px solid #DDE2E8;
  border-bottom:none;
  border-radius: 5px 5px 0 0;
}
.el-main {
  padding: 0;
  background-color:#fff;
  border:1px solid #DDE2E8;
}
.el-footer {
  height:45px;
  border-radius: 0 0 5px 5px;
  background-color:#fff;
  border:1px solid #DDE2E8;
  border-top:none;
}
/* .diyDialog :deep(.el-dialog__body) {
  padding: 0 !important;
}  */
/deep/ .el-dialog__body {
  padding: 0 15px 0 15px !important;
}
/deep/ .el-dialog {
  margin: 30px auto 30px !important;
  overflow: hidden !important;
}
/deep/ input[type='number'] {
  -moz-appearance: textfield;
}
</style>